from typing import Optional
from email_validator import validate_email, EmailNotValidError

from pydantic import BaseModel, field_validator

from fastapi import HTTPException


def its_empty_text(string: Optional[str]) -> bool:
    if string is None:
        return True
    string = string.replace(" ", "")
    if len(string) == 0:
        return True
    return False


class Registration_form(BaseModel):
    firstName: Optional[str]
    lastName: Optional[str]
    email: Optional[str]
    password: Optional[str]

    @field_validator('firstName')
    @classmethod
    def validate_firstName(cls, firstName: Optional[str]):
        if its_empty_text(firstName):
            raise HTTPException(status_code=400, detail="bad user's data")
        return firstName

    @field_validator('lastName')
    @classmethod
    def validate_lastName(cls, lastName: Optional[str]):
        if its_empty_text(lastName):
            raise HTTPException(status_code=400, detail="bad user's data")
        return lastName

    @field_validator('email')
    @classmethod
    def validate_email(cls, email: Optional[str]):
        if its_empty_text(email):
            raise HTTPException(status_code=400, detail="bad user's data")

        try:
            validate_email(email)
        except EmailNotValidError:
            raise HTTPException(status_code=401, detail="bad email")

        return email

    @field_validator('password')
    @classmethod
    def validate_password(cls, password: Optional[str]):
        if its_empty_text(password):
            raise HTTPException(status_code=400, detail="bad user's data")
        return password


class Login_form(BaseModel):
    email: str
    password: str

    @field_validator('email')
    @classmethod
    def validate_email(cls, email: Optional[str]):
        if its_empty_text(email):
            return "0"

        try:
            validate_email(email)
        except EmailNotValidError:
            return "0"

        return email


class Update_form(Registration_form):
    firstName: Optional[str] = None
    lastName: Optional[str] = None
    email: Optional[str] = None
    password: Optional[str] = None


class My_account(BaseModel):
    id: int
    firstName: str
    lastName: str
    email: str


class Auth_record(BaseModel):
    id: Optional[int] = None
    firstName: str
    lastName: str
    email: str
    password: str


class id_schema(BaseModel):
    id: int
